package com.qingcloud.common.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.qingcloud.common.auth.service.IValidateCodeService;
import com.qingcloud.base.api.remote.admin.AdminApi;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.pojo.Result;
import com.qingcloud.common.redis.template.RedisUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class ValidateCodeServiceImpl implements IValidateCodeService {
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private AdminApi adminApi;

    /**
     * 保存用户验证码，和randomStr绑定
     *
     * @param validId 客户端生成
     * @param imageCode 验证码信息
     */
    @Override
    public void saveImageCode(String validId, String imageCode) {
        redisUtil.set(buildKey(validId), imageCode,SecurityConstants.DEFAULT_IMAGE_EXPIRE);
    }

    /**
     * 发送验证码
     * @param mobile 手机号
     * @return true、false
     */
    @Override
    public Result sendSmsCode(String mobile) {

        return Result.success("true");
    }

    /**
     * 获取验证码
     * @param validId 前端唯一标识/手机号
     */
    @Override
    public String getCode(String validId) {
        return (String)redisUtil.get(buildKey(validId));
    }

    /**
     * 删除验证码
     * @param validId 前端唯一标识/手机号
     */
    @Override
    public void remove(String validId) {
        redisUtil.del(buildKey(validId));
    }

    /**
     * 验证验证码
     */
    @SneakyThrows
    @Override
    public void validate(String validId, String validCode) {
        if (StrUtil.isBlank(validId)) {
            throw new Exception("请在请求参数中携带validId参数");
        }
        String code = this.getCode(validId);
        if (StrUtil.isBlank(validCode)) {
            throw new Exception("请填写验证码");
        }

        if (code == null) {
            throw new Exception("验证码不存在或已过期");
        }

        if (!StrUtil.equals(code, validCode.toLowerCase())) {
            throw new Exception("验证码不正确");
        }

        this.remove(validId);
    }

    private String buildKey(String deviceId) {
        return SecurityConstants.DEFAULT_CODE_KEY + ":" + deviceId;
    }
}
